package com.hyb.Realm;

import com.hyb.Util.JwtUtil;
import com.hyb.entity.Role;
import com.hyb.entity.Staff;
import com.hyb.mapper.PermissionMapper;
import com.hyb.service.RoleService;
import com.hyb.service.StaffService;
import com.hyb.token.JwtToken;
import io.jsonwebtoken.Claims;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * <p>
 *      realm(权限控制和安全认证)
 * </p>
 *
 * @author hyb
 * @since 2021-12-29
 */
@Component
public class MyRealm extends AuthorizingRealm {
    @Autowired
    private StaffService staffService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String staffEmail = (String) principalCollection.iterator().next();
//        System.out.println(staffEmail);
        Set<String> roles = roleService.getRolesByStaffEmail(staffEmail);
        Set<String> permissions = permissionMapper.getPermissionServiceByStaffEmail(staffEmail);

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(permissions);

        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        JwtToken jwtToken = (JwtToken) token;
        String jwt = (String) jwtToken.getPrincipal();
        Claims claims = JwtUtil.parseJWT(jwt);
        String staffEmail = claims.getId();

        Staff staff = staffService.getStaffBuyStaffEmail(staffEmail);
        if (staff == null){
            return null;
        }
        return new SimpleAuthenticationInfo(staffEmail,staff.getStaffPassword(),getName());
    }
}
